package com.szcinda.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.szcinda.controller.configuration.UserLoginToken;
import com.szcinda.repository.Line;
import com.szcinda.service.dto.line.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("line")
public class LineController {

    private final LineService lineService;

    public LineController(LineService lineService) {
        this.lineService = lineService;
    }


    @UserLoginToken
    @PostMapping("create")
    @OperationLogAnnotation(operDesc = "新增线路", operModel = "线路维护")
    public Result<String> create(@RequestBody LineCreateDto createDto) {
        lineService.create(createDto);
        return Result.success();
    }

    @GetMapping("del/{id}/{userId}")
    @OperationLogAnnotation(operDesc = "删除线路", operModel = "线路维护")
    public Result<String> del(@PathVariable String id, @PathVariable String userId) {
        lineService.delete(id, userId);
        return Result.success();
    }

    @UserLoginToken
    @PostMapping("getAll")
    public Result<List<Line>> query(@RequestBody LineQueryDto queryDto) {
        return Result.success(lineService.findAll(queryDto));
    }

    @PostMapping("search")
    public Result<List<Line>> all(@RequestBody LineQueryDto queryDto) {
        return Result.success(lineService.search(queryDto));
    }

    @PostMapping("/import/{opId}")
    @OperationLogAnnotation(operDesc = "导入线路", operModel = "线路维护")
    public Result<String> orderImport(@RequestParam("file") MultipartFile file, @PathVariable String opId) throws Exception {
        // 解析每行结果在listener中处理
        InputStream inputStream = file.getInputStream();
        try {
            LineExcelListener listener = new LineExcelListener();
            EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, LineImportDto.class), listener);
            lineService.batchCreate(listener.getImportDatas(), opId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
